/**
 * 
 */
package com.jie.eclipse.pan.popup.actions;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

import org.eclipse.core.internal.resources.File;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jst.jsp.core.internal.domdocument.ElementImplForJSP;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.FileEditorInput;

import com.jie.eclipse.pan.dao.QMDao;
import com.jie.eclipse.pan.editors.editor.JSPEditor;
import com.jie.eclipse.pan.utils.StringHelper;
import com.jie.eclipse.pan.utils.Utils;
import com.jie.eclipse.pan.utils.handle.FileHandle;

/**
 * @author yanjie
 *
 */
public class CopyPageAction implements IObjectActionDelegate{
	
	private Shell shell;
	private IWorkbenchPart targetPart;
	private List<File> files= null;
	private IAction at = null; 
	
	public void run(IAction action) {
		at = action;
		ISelection selection = targetPart.getSite().getSelectionProvider().getSelection();
		
		if(files == null){
			files = new ArrayList<File>();
		}else{
			files.clear();
		}
		
		if(targetPart.getSite().getPart() instanceof JSPEditor){
			JSPEditor editor = (JSPEditor)targetPart.getSite().getPart();
			IEditorInput input = editor.getEditorInput();
			if(input instanceof FileEditorInput){
				FileEditorInput fileInput = (FileEditorInput)input;
				if (fileInput.getFile() instanceof File) {
					files.add((File)fileInput.getFile());
				}
								
			}
			
		}else if (selection instanceof TreeSelection) {
			TreeSelection ts = (TreeSelection) selection;
			Iterator it = ts.iterator();
			// TODO 相应的业务逻辑
			while (it.hasNext()) {
				Object obj = it.next();
				if (obj instanceof File) {
					files.add((File)obj);
				}
			}
		}
		
		ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
		IRunnableWithProgress rwp = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) {
				// totalWork为IProgressMonitor.UNKNOWN时表示不知道任务的总量
				// 将在进度条上显示一个来回移动的进度条
				try {
					Map<String,String> map = new HashMap<String, String>();
					map.put("10", "info-asp1");
					map.put("16", "info-asp2");
					map.put("19", "info-asp31");
					map.put("21", "yanjie3");
					String userName = QMDao.getInstance().getCurLogUserName();
					
					monitor.beginTask("正在发布页面", IProgressMonitor.UNKNOWN);
					// monitor.beginTask("发布页面", taskSize);
					Iterator it = files.iterator();
					// TODO 相应的业务逻辑
					while (it.hasNext()) {
						Object obj = it.next();
						if (obj instanceof File) {
							File file = (File) obj;
							if (file.getFileExtension().equals("jsp") || ("yanjie".equals(userName) || "dwei".equals(userName))) {
								java.io.File jfile = new java.io.File(file.getLocation().toOSString());
								String fpath = file.getFullPath().toString().replace("WebRoot/", "");
								
								String hosts[] = at.getText().replace("主机", "").split(",");
								String hostIp = "";
								String hostName = "";
								for (int i = 0; i < hosts.length; i++) {
									hostName = hosts[i]+"主机";
									//hostIp = "169.169.0."+hosts[i];
									hostIp = StringHelper.getValue(map.get(hosts[i]), "169.169.0."+hosts[i]) ;
									monitor.setTaskName("正在发布页面: "+jfile.getName()+" 至 "+hostName);
									copyFile(jfile, hostIp+"/tomcat$/webapps"+ fpath, jfile.getName(), hostName);
									//copyFile(jfile, "info-asp2/tomcat$/webapps"+ fpath, jfile.getName(), hostName);
									recordJspInfo(file,fpath);
									//TimeUnit.MILLISECONDS.sleep(100L);
								}
								
							}
						}
					}
				} catch (Exception e) {
					Utils.print(e.getMessage());
				}
				monitor.done();
			}
		};
		
		try {pmd.run(true, false, rwp);} catch (Exception e) {e.printStackTrace();}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction arg0, ISelection arg1) {
		
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
		this.targetPart = targetPart;
		
	}
	
	private void copyFile(java.io.File jfile,String newPath,String fileName,String hostName){
		try {
			int bytesum = 0;
			int byteread = 0;
			if (jfile.exists()) {
				String user = "jmknit.com;js:jmjs";
				NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
				
				SmbFile dfilepath = new SmbFile("smb://"+newPath.replace(fileName, ""),auth);
				if(!dfilepath.exists()){dfilepath.mkdirs();}
				
				InputStream inStream = new FileInputStream(jfile);
				SmbFile smbFile = new SmbFile("smb://"+newPath,auth);
				SmbFileOutputStream fs = new SmbFileOutputStream(smbFile);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			Utils.print(fileName+" 发布 至 "+hostName+" 完成!");
		} catch (Exception e) {
			Utils.print(fileName+" 发布 至 "+hostName+" 失敗!"+e.getMessage());
		}
	}
	
	private void recordJspInfo(File file,String newPath){
		FileHandle fh = new FileHandle(file);
		ElementImplForJSP node = fh.getPageProperty(fh.getUidomDoc(), false);
		
		String pageName = "";
		String userName = QMDao.getInstance().getCurLogUserName();
		
		boolean boverwriter = true;
		if(node != null){
			pageName = node.getTextContent().trim();
			Pattern   pat   =   Pattern.compile("page1.getPageTitle\\(\\).setTitle\\(\"([^\"]*)\"\\);");
			Matcher   mat   =pat.matcher(pageName);
			if(mat.find()){
				pageName = mat.group().replace("page1.getPageTitle().setTitle(\"", "").replace("\");", "");
			}else{
				pageName = file.getName();
			}
		}else{
			boverwriter = false;
			pageName = file.getName();
		}
		
		if(!QMDao.getInstance().getJspInfoMap().containsKey(pageName)){
			String ip = "";
			try {
				InetAddress addr=InetAddress.getLocalHost();
				ip = addr.getHostAddress();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			QMDao.getInstance().getJspInfoMap().put(newPath, pageName);
			QMDao.getInstance().registerJspInfo(newPath, pageName, userName,ip,boverwriter);
		}
	}
}
